package crazyboyfeng.autodroid.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import crazyboyfeng.autodroid.R;
import crazyboyfeng.autodroid.adapter.TaskAdapter;
import crazyboyfeng.autodroid.bean.TaskBean;
import crazyboyfeng.autodroid.tasks.TaskManager;

public class MainActivity extends Activity {
 
	TaskManager mTM = new TaskManager();
	TaskAdapter taskAdapter;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initListView();
    } 

    private void initListView(){
        ListView list = (ListView) findViewById(R.id.listAll);
        taskAdapter = new TaskAdapter(this,mTM.getAllTaskList());
        list.setAdapter(taskAdapter);
        list.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
            	goNext(taskAdapter.getItem(position));
            }

        });
        taskAdapter.notifyDataSetChanged();
    }

    public void onResume() {
        super.onResume();  // Always call the superclass method first
        initListView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menus_main, menu);
        return true;
    }
    
    public void goNext(TaskBean task){
    	Intent intent = new Intent(this, AddNewTaskActivity.class);
    	intent.putExtra("taskId", task.getId());
    	startActivity(intent);
    	overridePendingTransition(R.anim.slide_in_up,R.anim.slide_out_up);  
    }
    
    
    @Override
	public boolean onOptionsItemSelected (MenuItem item){
    	if(item.getItemId()==R.id.menu_new){
    		addNewTask();
    	}else if(item.getItemId()==R.id.menu_open){
    		openTasks();
    	}else if(item.getItemId()==R.id.menu_settings){
    		Intent intent = new Intent(this, SettingActivity.class);
    		this.startActivity(intent);
    		overridePendingTransition(R.anim.slide_in_up,R.anim.slide_out_up);  
    	}
		return true;
    }
    
    private void openTasks() {
    	try {
            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
                File dir = new File(Environment.getExternalStorageDirectory().getCanonicalPath()+ "/Autodroid");
                dir.mkdirs();
                File[] targets=dir.listFiles();
                int number=0;
                for (File target : targets) {
					if(target.getName().endsWith(".task")){
						FileInputStream fis = new FileInputStream(target);
			            ObjectInputStream ois = new ObjectInputStream(fis);
			            TaskBean task = (TaskBean)ois.readObject();
			            mTM.addTask(task);
			            number++;
			            target.delete();
			            ois.close();
					}
				}
            	initListView();
                Toast.makeText(getApplicationContext(), "共导入"+number+"个任务！",Toast.LENGTH_SHORT).show();
            }else{
            	Toast.makeText(getApplicationContext(), "没有检测到外部存储！",Toast.LENGTH_SHORT).show();
            }
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public void addNewTask(){
    	 mTM.addNewTask();
    	initListView();
    }
}
